<template>
    <div class="container">
      <label>
        <input :value="inputValue" @change="handleInputChange" type="text" />
        <button @click="addItemToList">添加</button>
      </label>
      <div class="table">
        <ul>
          <li v-for="(item, index) in infoList" :key="index">
            <label> <input :checked="item.done" type="checkbox" @change="watchCheckedStatus(item.id, $event)" />{{item.info}} </label>
            <span @click="deleteItemToList(item.id)">删除</span>
          </li>
        </ul>
        <div class="foot">
          <span>未完成{{unDoneLength}}条</span>
          <button :class="[itemKey ==='all'? 'btn-active' : '']" @click="changeList('all')">全部</button>
          <button :class="[itemKey ==='done'? 'btn-active' : '']" @click="changeList('done')">已完成</button>
          <button :class="[itemKey ==='undone'? 'btn-active' : '']" @click="changeList('undone')">未完成</button>
          <span @click="cleanItem" style="color:blue;cursor:pointer;">清楚已完成</span>
        </div>
      </div>
      <button @click="testActions">actions</button>
      <button @click="testActions2">actions</button>
    </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'

export default {
  computed: {
    ...mapState(['inputValue', 'itemKey']),
    ...mapGetters(['unDoneLength', 'infoList'])
  },
  created () {
    /* 调用store实例下actions对象中的getList方法 dispatch为派遣的意思 */
    this.$store.dispatch('getList')
  },
  methods: {
    testActions () {
      this.$store.dispatch('test').then(res => {
        console.log(res)
      })
    },
    testActions2 () {
      this.$store.dispatch('test2').then(res => {
        console.log(res)
      })
    },
    handleInputChange (e) {
      this.$store.commit('setInputValue', e.target.value)
    },
    /* 添加记录 */
    addItemToList () {
      if (this.inputValue.trim().length <= 0) {
        return false
      }
      this.$store.commit('addItem')
    },
    /* 删除记录 */
    deleteItemToList (id) {
      this.$store.commit('deleteItem', id)
    },
    /* 监听复框状态 */
    watchCheckedStatus (id, e) {
      const param = {
        id,
        status: e.target.checked
      }
      this.$store.commit('changeStatus', param)
    },
    /* 清除已完成 */
    cleanItem () {
      this.$store.commit('clean')
    },
    changeList (key) {
      this.$store.commit('switchItem', key)
    }
  }
}
</script>

<style>
* {
  list-style: none;
  margin: 0;
  padding: 0;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.container {
  width: 500px;
}
.table {
  border: 1px solid #ccc;
  padding: 10px;
  margin-top: 20px;
}
ul li {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #ccc;
  padding: 10px;
}
li input {
  margin-right: 10px;
}
li span {
  color: cornflowerblue;
  cursor: pointer;
}
.foot {
  padding: 10px 0;
}
.foot button {
  margin: 0 10px;
}
.btn-active {
  background-color: cyan;
}
</style>
